package com.Pan.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.Data;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author yangtao
 * @Description 计算多边形重心坐标
 * @Date 2020/3/31 16:15
 **/
public class CalculateArealCoordinateUtil {

    public static String getArealCoordinate(String muiltyCoordinate) {

        List<LatLng> latLngList = Lists.newArrayList();

        List<List<Integer>> list = JSONObject.parseObject(muiltyCoordinate, List.class);
        for (List<Integer> coordinate : list ) {
            LatLng latLng = new LatLng();
            latLng.setLatitude(coordinate.get(0));
            latLng.setLongitude(coordinate.get(1));
            latLngList.add(latLng);
        }
        LatLng arealCoordinate = getCenterOfGravityPoint(latLngList);
        System.out.println(arealCoordinate);
        String result = new BigDecimal(String.valueOf(arealCoordinate.getLatitude())).setScale(2, BigDecimal.ROUND_DOWN).toString()
                + ","
                + new BigDecimal(String.valueOf(arealCoordinate.getLongitude())).setScale(2, BigDecimal.ROUND_DOWN).toString();
        return result;
    }


    private static LatLng getCenterOfGravityPoint(List<LatLng> mPoints) {
        //多边形面积
        Double area = 0.0;
        // 重心的x、y
        Double Gx = 0.0, Gy = 0.0;
        for (int i = 1; i <= mPoints.size(); i++) {
            Double iLat = mPoints.get(i % mPoints.size()).latitude;
            Double iLng = mPoints.get(i % mPoints.size()).longitude;
            Double nextLat = mPoints.get(i - 1).latitude;
            Double nextLng = mPoints.get(i - 1).longitude;
            Double temp = (iLat * nextLng - iLng * nextLat) / 2.0;
            System.out.println(temp);
            area += temp;
            Gx += temp * (iLat + nextLat) / 3.0;
            System.out.println(Gx);
            Gy += temp * (iLng + nextLng) / 3.0;
            System.out.println(Gx);
        }
        Gx = Gx / area;
        Gy = Gy / area;
        if (Gx.isNaN()) {
            Gx = mPoints.get(0).getLatitude();
        }
        if (Gy.isNaN()) {
            Gy = mPoints.get(0).getLongitude();
        }
        LatLng latLng = new LatLng();
        latLng.setLatitude(Gx);
        latLng.setLongitude(Gy);
        return latLng;

    }

    @Data
    private static class LatLng {
        private double latitude;
        private double longitude;
    }


}
